import json

import requests

from utils.log_util import logger_for_requests


# 接口请求操作封装
class RequestClient:

    def __init__(self):
        self.response = {}
        self.session = requests.session()

    def get(self, url, **kwargs):
        return self.request(url, 'GET', **kwargs)

    def post(self, url, **kwargs):
        return self.request(url, 'POST', **kwargs)

    def put(self, url, **kwargs):
        return self.request(url, 'PUT', **kwargs)

    def delete(self, url, **kwargs):
        return self.request(url, 'DELETE', **kwargs)

    def request(self, url, method, **kwargs):
        data = dict(**kwargs).get('data')
        json_data = dict(**kwargs).get('json')
        params = dict(**kwargs).get('params')
        headers = dict(**kwargs).get('headers')

        logger_for_requests.info(f"请求接口地址>>>{url}")
        logger_for_requests.info(f"请求接口方式>>>{method}")
        if data is not None:
            logger_for_requests.info(f"请求接口参数data>>>\n{json.dumps(data,indent=2,ensure_ascii=False)}")
        if json_data is not None:
            logger_for_requests.info(f"请求接口参数json>>>\n{json.dumps(json_data,indent=2,ensure_ascii=False)}")
        if params is not None:
            logger_for_requests.info(f"请求接口参数params>>>\n{json.dumps(params,indent=2,ensure_ascii=False)}")
        if headers is not None:
            logger_for_requests.info(f"请求接口参数headers>>>\n{json.dumps(headers,indent=2,ensure_ascii=False)}")
        if method == 'GET':
            self.response = self.session.get(url, **kwargs)
        elif method == 'POST':
            self.response = self.session.post(url, **kwargs)
        elif method == 'PUT':
            self.response = self.session.put(url, **kwargs)
        elif method == 'DELETE':
            self.response = self.session.delete(url, **kwargs)
        logger_for_requests.info(f"响应状态码>>>{self.response.status_code}")
        try:
            response_json = self.response.json()
            logger_for_requests.info(f"响应内容>>>\n{json.dumps(response_json, indent=2, ensure_ascii=False)}")
        except requests.exceptions.JSONDecodeError:
            logger_for_requests.warning("响应内容不是有效的 JSON")
            logger_for_requests.info(f"原始响应内容>>>\n{self.response.text}")
        return self.response

